<?php

class SogouScript extends ScriptBase
{
    private $scrapy = null;
    private $redis = null;
    private $cookieJson = null;
    private $cookieStr = null;

    public function __construct()
    {
        $this->scrapy = n_api('scrapy');
        $this->redis = n_api('redis')->scrapy;
    }

    /**
     * 搜狗cookie中随机SUV的生成
     * @return string
     */
    public function getSUV()
    {
        $timestamp = floor(microtime(true) * 1000);
        $rand = mt_rand(101, 999);
        return (string)$timestamp * 1000 + $rand;
    }

    /**
     * 处理从各处采集的cookie文件
     * @throws CException
     */
    public function handleText()
    {
        $taskId = 'sogou';
        $path = '/opt/allcookies.log';

        $fetch = file_get_contents($path);
        $a = explode('  ', trim($fetch));

        foreach ($a as $b) {
            $c = json_decode($b, true);
            $c[] = ['Name' => 'SUV', 'Value' => (string)$this->getSUV()];
            $this->scrapy->addCookie($taskId, json_encode($c));
        }
    }

    public function getCookie()
    {
        $url = 'http://weixin.sogou.com/weixin?type=1&query=%E5%93%88%E5%93%88&ie=utf8';

        while(true) {
            $len = $this->redis->lLen("scrapyCookie-=-sogou");
            if ($len >= 30)
                $this->redis->lpop("scrapyCookie-=-sogou");

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding: gzip, deflate, sdch',
                'Accept-Language: zh-CN,zh;q=0.8',
                'Cache-Control: max-age=0',
                'Connection: keep-alive',
                'Host: weixin.sogou.com',
                'Referer: http://weixin.sogou.com/weixin?type=2&query=%E6%88%91%E5%8E%BB&ie=utf8',
                'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36'
            ]);
            $rs = curl_exec($ch);

            $cookies = [];
            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
                preg_match_all('/Set-Cookie:(.*);/iU', $rs, $str);
                foreach ($str[1] as $value) {
                    $tmp = explode('=', $value);
                    if (!empty($tmp[0]) && !empty($tmp[1])) {
                        $name = trim($tmp[0]);
                        $value = trim($tmp[1]);
                        if ($name != 'black_passportid') {
                            $cookies[] = ['Name' => $name, 'Value' => $value];
                        }
                    }
                }
                echo "OK\n";
            } else {
                echo "fuck\n";
                sleep(3600 * 6);
                continue;
            }

            if (count($cookies) > 0) {
                $cookies[] = ['Name' => 'SUV', 'Value' => (string)$this->getSUV()];
                $this->scrapy->addCookie('sogou', json_encode($cookies));
            }

            sleep(120);
        }
    }

    private function getCookieStr() {
        if (is_null($this->cookieStr)) {
            $this->cookieJson = $this->scrapy->getTaskCookies('sogou')[0];
            $cookies = json_decode($this->cookieJson, true);
            $cookiesArr = [];
            foreach ($cookies as $cookie) {
                $cookiesArr[] = $cookie['Name'] . '=' . $cookie['Value'];
            }
            $this->cookieStr = implode('; ', $cookiesArr);
        }
        return $this->cookieStr;
    }

    private function curlGet($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language: zh-CN,zh;q=0.8',
            'Connection: keep-alive',
            'Host: weixin.sogou.com',
            'Referer: http://weixin.sogou.com/',
        ]);
        curl_setopt($ch, CURLOPT_COOKIE, $this->getCookieStr());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $rs['rs'] = curl_exec($ch);
        $rs['info'] = curl_getinfo($ch);

        return $rs;
    }

    private function handleContent($content) {

    }

    private function handleDescAuth($wxid, $wxname) {
        $url = 'http://weixin.sogou.com/weixin?type=1&query=' . urlencode($wxname) . '&ie=utf8';
        $rs = $this->curlGet($url);
        
        if ($rs['info']['code'] == 200)
            $this->handleContent($rs['rs']);

        $this->scrapy->addCookie('sogou', $cookieJson);
    }

    public function addWeixinMain()
    {
        $query = "select wxid, wxname from weixin_main_new where isdel = 'N' and flag = 0";
        $rs = $this->mysql->select($query);

        foreach ($rs as $value) {
            $wxid = $value['wxid'];
            $wxname = $value['wxname'];
            $this->handleDescAuth($wxid, $wxname);
            break;
        }
    }
}